package com.lolongmaps.main;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.lolongmaps.test.DBHelper;
import com.lolongmaps.test.Generator;
import com.lolongmaps.test.R;
import com.lolongmaps.test.Sorter;
import com.lolongmaps.model.Details;
import com.lolongmaps.model.User;

public class SuggestionView extends Activity implements View.OnClickListener{
	
	Button typeFastfood, typeRestaurant, typeCafe, typeBDD,
	foodAmerican, foodCoffee, foodChinese, foodDessert, foodFilipino,
	foodItalian, foodJapanese, foodKorean, foodBread,
	areaAyalaCBD, areaGlorietta5;
	
	ImageButton findMeRestaurantButton, surpriseMeButton;;

	ArrayList<Button> restaurantButtons, foodButtons, areaButtons;
	ArrayList<Integer> restaurantIDs, foodIDs, areaIDs; 

	Intent intent;
	User user;
	Details detail;
	Class choiceView;
	Generator generator;
	DBHelper myHelper;
	Sorter sorter;

	ScrollView scrollView;
	LinearLayout mainLayout, linearLayout;

	int restaurantNumber, foodNumber, areaNumber;
	boolean isFirstSpin, rButtonsFlag, fButtonsFlag, aButtonsFlag;
	
    public void onCreate(Bundle savedInstanceState) {
    	
        super.onCreate(savedInstanceState);
        setContentView(R.layout.suggestion);
     
        this.detail = new Details();
        this.generator = new Generator();
        intent = getIntent();
		user = (User)intent.getSerializableExtra("userObject");
        
        this.restaurantButtons = new ArrayList<Button>();
	    this.foodButtons = new ArrayList<Button>();
	    this.areaButtons = new ArrayList<Button>();
	    this.restaurantIDs = new ArrayList<Integer>();
	    this.foodIDs = new ArrayList<Integer>();
	    this.areaIDs = new ArrayList<Integer>();
		
	    this.isFirstSpin = true;
	    this.rButtonsFlag = false;
	    this.fButtonsFlag = false;
	    this.aButtonsFlag = false;
	    
	    this.mainLayout = (LinearLayout) findViewById(R.id.mainLayout);
		
		this.createButtons();
        
        
        try {
        	
			this.choiceView = Class.forName("com.lolongmaps.main.InformationView");
			this.intent = new Intent(SuggestionView.this, this.choiceView);
			this.intent.putExtra("detailsObject", this.detail);
			
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
    }
    
    public void createButtons() {
		
		//Restaurant Types
		typeFastfood = (Button) findViewById(R.id.suggestionButtonFastfood);
		typeFastfood.setOnClickListener(this);
		this.restaurantButtons.add(typeFastfood);
		this.restaurantIDs.add(R.drawable.fastfood1);
						
		typeRestaurant = (Button) findViewById(R.id.suggestionButtonRestaurant);
		typeRestaurant.setOnClickListener(this);
		this.restaurantButtons.add(typeRestaurant);
		this.restaurantIDs.add(R.drawable.restaurant1);
						
		typeCafe = (Button) findViewById(R.id.suggestionButtonCafe);
		typeCafe.setOnClickListener(this);
		this.restaurantButtons.add(typeCafe);
		this.restaurantIDs.add(R.drawable.cafe1);
						
		typeBDD = (Button) findViewById(R.id.suggestionButtonBDD);
		typeBDD.setOnClickListener(this);
		this.restaurantButtons.add(typeBDD);
		this.restaurantIDs.add(R.drawable.cake1);
						
						
		//Food Types
		foodAmerican = (Button) findViewById(R.id.suggestionButtonAmerican);
		foodAmerican.setOnClickListener(this);
		this.foodButtons.add(foodAmerican);
		this.foodIDs.add(R.drawable.american1);
						
		foodCoffee = (Button) findViewById(R.id.suggestionButtonCoffee);
		foodCoffee.setOnClickListener(this);
		this.foodButtons.add(foodCoffee);
		this.foodIDs.add(R.drawable.coffee1);
						
		foodChinese = (Button) findViewById(R.id.suggestionButtonChinese);
		foodChinese.setOnClickListener(this);
		this.foodButtons.add(foodChinese);
		this.foodIDs.add(R.drawable.chinese1);
						
		foodDessert = (Button) findViewById(R.id.suggestionButtonDessert);
		foodDessert.setOnClickListener(this);
		this.foodButtons.add(foodDessert);
		this.foodIDs.add(R.drawable.dessert1);
								
		foodFilipino = (Button) findViewById(R.id.suggestionButtonFilipino);
		foodFilipino.setOnClickListener(this);
		this.foodButtons.add(foodFilipino);
		this.foodIDs.add(R.drawable.filipino1);
						
		foodItalian = (Button) findViewById(R.id.suggestionButtonItalian);
		foodItalian.setOnClickListener(this);
		this.foodButtons.add(foodItalian);
		this.foodIDs.add(R.drawable.italian1);
						
		foodJapanese = (Button) findViewById(R.id.suggestionButtonJapanese);
		foodJapanese.setOnClickListener(this);
		this.foodButtons.add(foodJapanese);
		this.foodIDs.add(R.drawable.japanese1);
						

		foodKorean = (Button) findViewById(R.id.suggestionButtonKorean);
		foodKorean.setOnClickListener(this);
		this.foodButtons.add(foodKorean);
		this.foodIDs.add(R.drawable.korean1);
				
		foodBread = (Button) findViewById(R.id.suggestionButtonBread);
		foodBread.setOnClickListener(this);
		this.foodButtons.add(foodBread);
		this.foodIDs.add(R.drawable.bread1);
				
							
		//Areas
		areaAyalaCBD = (Button) findViewById(R.id.suggestionButtonAyalaCBD);
		areaAyalaCBD.setOnClickListener(this);
		this.areaButtons.add(areaAyalaCBD);
		this.areaIDs.add(R.drawable.ayala1);
						
		areaGlorietta5 = (Button) findViewById(R.id.suggestionButtonGlorietta5);
		areaGlorietta5.setOnClickListener(this);
		this.areaButtons.add(areaGlorietta5);
		this.areaIDs.add(R.drawable.glorietta1);
						
						
		//Find Button
		findMeRestaurantButton = (ImageButton) findViewById(R.id.suggestionButtonSuggestResto);
		findMeRestaurantButton.setOnClickListener(this);
					
		surpriseMeButton = (ImageButton) findViewById(R.id.suggestionButtonSurpriseMe);	
		surpriseMeButton.setOnClickListener(this);
		
		this.completeLists();
				
	}
    	
    	
    private void completeLists() {
		
    	this.restaurantIDs.add(R.drawable.fastfood);
    	this.restaurantIDs.add(R.drawable.restaurant);
    	this.restaurantIDs.add(R.drawable.cafe);
    	this.restaurantIDs.add(R.drawable.cake);
		
    	this.foodIDs.add(R.drawable.american);
    	this.foodIDs.add(R.drawable.coffee);
    	this.foodIDs.add(R.drawable.chinese);
    	this.foodIDs.add(R.drawable.dessert);
    	this.foodIDs.add(R.drawable.filipino);
    	this.foodIDs.add(R.drawable.italian);
    	this.foodIDs.add(R.drawable.japanese);
    	this.foodIDs.add(R.drawable.korean);
    	this.foodIDs.add(R.drawable.bread);
		
    	this.areaIDs.add(R.drawable.ayala);
    	this.areaIDs.add(R.drawable.glorietta);
	
    }
    
    public void onClick(View v) {
	// TODO Auto-generated method stub
    			
    	switch(v.getId()) {
    			
	    	//Restaurant Types
	    	case R.id.suggestionButtonFastfood:				
	    	this.setChoiceAndButtonImage('R', "Fastfood", v, R.drawable.fastfood, R.drawable.fastfood1);
	    	break;
	    	case R.id.suggestionButtonRestaurant:
	    	this.setChoiceAndButtonImage('R', "Restaurant", v, R.drawable.restaurant, R.drawable.restaurant1);
	    	break;
	    	case R.id.suggestionButtonCafe:				
	    	this.setChoiceAndButtonImage('R', "Cafe", v, R.drawable.cafe, R.drawable.cafe1);
	    	break;
	    	case R.id.suggestionButtonBDD:				
	    	this.setChoiceAndButtonImage('R', "Bakeshop, Desserts and Delicacies", v, R.drawable.cake, R.drawable.cake1);
	    	break;
	    					
	    					
	    	//Food Types
	    	case R.id.suggestionButtonAmerican:
	    		this.setChoiceAndButtonImage('F', "American", v, R.drawable.american, R.drawable.american1);
	    		break;
	    	case R.id.suggestionButtonCoffee:
	    		this.setChoiceAndButtonImage('F', "Coffee", v, R.drawable.coffee, R.drawable.coffee1);
	    		break;
	    	case R.id.suggestionButtonChinese:
	    		this.setChoiceAndButtonImage('F', "Chinese", v, R.drawable.chinese, R.drawable.chinese1);
	    		break;
	    	case R.id.suggestionButtonDessert:
	    		this.setChoiceAndButtonImage('F', "Dessert", v, R.drawable.dessert, R.drawable.dessert1);
	    		break;
	    	case R.id.suggestionButtonFilipino:
	    		this.setChoiceAndButtonImage('F', "Filipino", v, R.drawable.filipino, R.drawable.filipino1);
	    		break;
	    	case R.id.suggestionButtonItalian:
	    		this.setChoiceAndButtonImage('F', "Italian", v, R.drawable.italian, R.drawable.italian1);
	    		break;
	    	case R.id.suggestionButtonJapanese:
	    		this.setChoiceAndButtonImage('F', "Japanese", v, R.drawable.japanese, R.drawable.japanese1);
	    		break;
	    	case R.id.suggestionButtonKorean:
	    		this.setChoiceAndButtonImage('F', "Korean", v, R.drawable.korean, R.drawable.korean1);
	    		break;
	    	case R.id.suggestionButtonBread:
	    		this.setChoiceAndButtonImage('F', "Bread", v, R.drawable.bread, R.drawable.bread1);
	    		break;
	    					
	    					
	    	case R.id.suggestionButtonAyalaCBD:			
	    		this.setChoiceAndButtonImage('A', "Ayala Central Business District", v, R.drawable.ayala, R.drawable.ayala1);
	    		break;
	    	case R.id.suggestionButtonGlorietta5:
	    		this.setChoiceAndButtonImage('A', "Glorietta 5", v, R.drawable.glorietta, R.drawable.glorietta1);
	    		break;
	    					
	    					
	    					
	    	case R.id.suggestionButtonSuggestResto:
	    					
	    		Boolean connected = checkConn(SuggestionView.this);
	    		   		
	    		
	    		if(!isFirstSpin) {
	    						
	    			this.scrollView.removeAllViews();
	    						
	    			this.disableButtons('R');
	    			this.disableButtons('F');
	    			this.disableButtons('A');
	    						
	    			this.checkForNewSelection();
	    						
	    		}
	    					
	    					
	    		this.generateForEmptySlots();				
	    		this.findRestaurants();
	    		this.addViewsInLayout();	    					
	    		this.nullifyStuff();
	    			
	    		this.isFirstSpin = false;
	    				
	    		break;
	    			
	    	
	    	case R.id.suggestionButtonSurpriseMe:
	    		
	    		if(!isFirstSpin) {
	    			this.scrollView.removeAllViews();
	    		}
	    		
	    		aButtonsFlag = false;
	    		fButtonsFlag = false;
	    		rButtonsFlag = false;
	    	
	    		this.disableButtons('R');
    			this.disableButtons('F');
    			this.disableButtons('A');
	    		
    			this.nullifyStuff();
    			this.generateForEmptySlots();
	    		this.findRestaurants();
	    		this.addViewsInLayout();	 
	    		
	    		this.isFirstSpin = false;
	    		
	    		break;
	    		
    	}	
    }
    		
    private void addViewsInLayout() {
    			
    	this.scrollView = new ScrollView(this);
    	this.linearLayout = new LinearLayout(this);
    	linearLayout.setOrientation(LinearLayout.VERTICAL);
    	        
    	        
    	if(myHelper.getUsersRestaurantChoiceListContainer().isEmpty()) {
    	        	
    		TextView tv = new TextView(this);
    	  	tv.setText("No restaurants found.");
    	   	tv.setGravity(Gravity.CENTER);
    	   	linearLayout.addView(tv);
    	        	
    	} else {
    	        	
    		this.sorter = new Sorter(myHelper.getUsersRestaurantChoiceListContainer());
    		this.sorter.sort();
    		myHelper.setUsersRestaurantChoiceList(sorter.getRestaurants());

    		
    	   	for(int x=0; x<myHelper.getUsersRestaurantChoiceListContainer().size(); x++) {
    		    		
    		   final Button button = new Button(this);
    		   button.setId(x);
    		   button.setText((x+1) + "." + myHelper.getUsersRestaurantChoiceListContainer().get(x).getName());
    		   button.setBackgroundColor(Color.TRANSPARENT);
    		   button.setTextColor(Color.WHITE);
    		   final int y = x;
    		   button.setOnClickListener(new View.OnClickListener() {
    						
    						@Override
    				public void onClick(View v) {
    							// TODO Auto-generated method stub
    							
    					detail.setName(myHelper.getUsersRestaurantChoiceListContainer().get(y).getName());
    					detail.setType(myHelper.getUsersRestaurantChoiceListContainer().get(y).getType());
    					detail.setLocation(myHelper.getUsersRestaurantChoiceListContainer().get(y).getLocation());
    					detail.setArea(myHelper.getUsersRestaurantChoiceListContainer().get(y).getArea());
    					detail.setContactDetails(myHelper.getUsersRestaurantChoiceListContainer().get(y).getContactDetails());
    				    detail.setPrice(myHelper.getUsersRestaurantChoiceListContainer().get(y).getPrice());
    				   	detail.setDeliveryStatus(myHelper.getUsersRestaurantChoiceListContainer().get(y).getDeliveryStatus());
    				    detail.setWifiStatus(myHelper.getUsersRestaurantChoiceListContainer().get(y).getWifiStatus());
    				    detail.setOpen24hrsStatus(myHelper.getUsersRestaurantChoiceListContainer().get(y).getOpen24hrsStatus());
    				    detail.setParkigStatus(myHelper.getUsersRestaurantChoiceListContainer().get(y).getParkigStatus());
    				    detail.setCreditCardStatus(myHelper.getUsersRestaurantChoiceListContainer().get(y).getCreditCardStatus());
    				    detail.setBuffetStatus(myHelper.getUsersRestaurantChoiceListContainer().get(y).getBuffetStatus());
    				    detail.setCateringStatus(myHelper.getUsersRestaurantChoiceListContainer().get(y).getCateringStatus());
    				    detail.setFunctionsStatus(myHelper.getUsersRestaurantChoiceListContainer().get(y).getFunctionsStatus());
    				    detail.setReservationStatus(myHelper.getUsersRestaurantChoiceListContainer().get(y).getReservationStatus());
    				    detail.setEntertainmentStatus(myHelper.getUsersRestaurantChoiceListContainer().get(y).getEntertainmentStatus());
    				    detail.setOffersVeganFoodStatus(myHelper.getUsersRestaurantChoiceListContainer().get(y).getOffersVeganFoodStatus());
    							
    					startActivity(intent);
    							
    				}
    		   });
    		   
    		   linearLayout.addView(button);
    	   	}
    	   	
    	        	
    	}
    	        
    		
    	    scrollView.addView(linearLayout);       
    	    mainLayout.addView(scrollView);
    			
    	}	
    		
    private void nullifyStuff() {
    	
    	if(!aButtonsFlag) this.user.setChosenArea("none");
    	if(!fButtonsFlag) this.user.setChosenFoodType("none");
    	if(!rButtonsFlag) this.user.setChosenRestaurantType("none");
    			
    	this.generator.nullifyStuff(aButtonsFlag, fButtonsFlag, rButtonsFlag);
    	
    }
    
    private void checkForNewSelection() {
    	
		String newChosenRestaurant = this.user.getChosenRestaurantType();
		String newChosenFood = this.user.getChosenFoodType();
		String newChosenArea = this.user.getChosenArea();
		
		if(!newChosenRestaurant.equals("none")){
			int index = this.generator.getRestaurantIndex(this.user.getChosenRestaurantType());
			this.selectGeneratedButtons('R', index);
		}
		
		if(!newChosenFood.equals("none")){
			int index = this.generator.getFoodIndex(this.user.getChosenFoodType());
			this.selectGeneratedButtons('F', index);
		}
		
		if(!newChosenArea.equals("none")){
			int index = this.generator.getAreaIndex(this.user.getChosenArea());
			this.selectGeneratedButtons('A', index);
		}
		
	}
    
    private void selectGeneratedButtons(char c, int num) {
		// TODO Auto-generated method stub
		char chosenChar = c;
		int number = num;
		
		switch(chosenChar) {
		
			case 'R':
				
				this.restaurantButtons.get(number).setBackgroundResource(this.restaurantIDs.get(number));
				break;
				
			case 'F':
				
				this.foodButtons.get(number).setBackgroundResource(this.foodIDs.get(number));
				break;
				
			case 'A':
				
				this.areaButtons.get(number).setBackgroundResource(this.areaIDs.get(number));
				break;
			
		}
		
	}
	
    public boolean checkConn(Context ctx) {
    	
        ConnectivityManager conMgr =  (ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo i = conMgr.getActiveNetworkInfo();
        
        if (i == null) {
        
        	return false;
        	
        }
         
        if (!i.isConnected()) {
        	
        	return false;
        	
        }
         
        if (!i.isAvailable()) {
        	
        	return false;
        	
        }
          
        return true;
        
    }
    
	public void findRestaurants(){
		
		myHelper = new DBHelper(this);
		myHelper.filterFood(user.getChosenFoodType());
		myHelper.filterMenu(myHelper.getFoodNumber());
		
		for(int i = 0; i < myHelper.getApplicableRestoMenuBasedContainer().size(); i++){
			
			int yeah = myHelper.getApplicableRestoMenuBasedContainer().get(i);
			myHelper.filterRestaurant(yeah, user.getChosenRestaurantType(), user.getUserBudget(), user.getChosenArea());
		}
		
		for(int y = 0; y < myHelper.getFinalFilteredRestaurantIdsContainer().size(); y++){
			
			int id = myHelper.getFinalFilteredRestaurantIdsContainer().get(y);
			myHelper.populateChoiceList(id);
			
		}
			
		
	}
	
	private void generateForEmptySlots() {
		
		if(user.getChosenRestaurantType().equals("none")){
			this.generator.generateRestaurant();
			this.user.setChosenRestaurantType(this.generator.getGeneratedRestaurant());
			this.selectGeneratedButtons('R', this.generator.getRestaurantNumber());
		}
			
		if(user.getChosenFoodType().equals("none"))	{		
			this.generator.generateFood();
			this.user.setChosenFoodType(this.generator.getGeneratedFood());
			this.selectGeneratedButtons('F', this.generator.getFoodNumber());
		}
				
		if(user.getChosenArea().equals("none"))	{
			this.generator.generateArea();
			this.user.setChosenArea(this.generator.getGeneratedArea());
			this.selectGeneratedButtons('A', this.generator.getAreaNumber());
		}
		
	}
	
	private void setChoiceAndButtonImage(char c, String ch, View v, int n, int p) {
		
		char category = c;
		String choice = ch;
		Button button = (Button) v;
		int normal = n;
		int pressed = p;
		
		switch(category) {
		
			case 'R': //for Restaurants
				
				this.disableButtons('R');
				
				if(user.getChosenRestaurantType().equals(choice)) { //user deselected(?) button					
					button.setBackgroundResource(normal);
					user.setChosenRestaurantType("none");	
					this.rButtonsFlag = false;
				} else { 					
					v.setBackgroundResource(pressed);
					user.setChosenRestaurantType(choice);	
					this.rButtonsFlag = true;
				}			
				
				break;
				
			case 'F': //for Food Types
				
				this.disableButtons('F');
				
				if(user.getChosenFoodType().equals(choice)) {					
					button.setBackgroundResource(normal);
					user.setChosenFoodType("none");	
					this.fButtonsFlag = false;
				} else {
					v.setBackgroundResource(pressed);
					user.setChosenFoodType(choice);
					this.fButtonsFlag = true;
				}
				
				break;
				
			case 'A': //for Area
				
				this.disableButtons('A');
				
				if(user.getChosenArea().equals(choice)) {				
					button.setBackgroundResource(normal);
					user.setChosenArea("none");
					this.aButtonsFlag = false;
				} else {					
					v.setBackgroundResource(pressed);
					user.setChosenArea(choice);
					this.aButtonsFlag = true;
				}
				
				break;
		
		}
		
	}
	
	
	private void disableButtons(char c) {
		
		char category = c;
		
		switch(category){
			case 'R':
				
				for(int x=0; x<restaurantButtons.size(); x++){
					restaurantButtons.get(x).setBackgroundResource(restaurantIDs.get(x+4));
				}
				break;
				
			case 'F':
				
				for(int x=0; x<foodButtons.size(); x++) {
					foodButtons.get(x).setBackgroundResource(foodIDs.get(x+9));
				}
				break;
				
			case 'A':
							
				for(int x=0; x<areaButtons.size(); x++){
					areaButtons.get(x).setBackgroundResource(areaIDs.get(x+2));
				}
				break;
			}
		
		
	}
}